package org.dromara.company.controller;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.admin.domain.bo.OrderBo;
import org.dromara.admin.domain.vo.OrderVo;
import org.dromara.admin.service.IOrderService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 公司端订单主表
 *
 * @author Lion Li
 * @date 2025-10-10
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/company/order")
public class OrderController extends BaseController {

    private final IOrderService orderService;

    /**
     * 查询自己主体的订单主表列表
     */
//    @SaCheckPermission("system:order:list")
    @GetMapping("/myOrderList")
    public TableDataInfo<OrderVo> myOrderList(OrderBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        if (userId == null) {
            throw new ServiceException("请先登录！");
        }
        bo.setCompanyId(userId);
        return orderService.queryPageMyOrderList(bo, pageQuery);
    }

    /**
     * 导出订单主表列表
     */
//    @SaCheckPermission("system:order:export")
    @Log(title = "订单主表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(OrderBo bo, HttpServletResponse response) {
        List<OrderVo> list = orderService.queryList(bo);
        ExcelUtil.exportExcel(list, "订单主（客户ID和供应商ID必须二选一，由应用程序保证）", OrderVo.class, response);
    }

    /**
     * 获取订单主表详细信息
     *
     * @param id 主键
     */
//    @SaCheckPermission("system:order:query")
    @GetMapping("/{id}")
    public R<OrderVo> getInfo(@NotNull(message = "主键不能为空")
                              @PathVariable Long id) {
        return R.ok(orderService.queryById(id));
    }

    /**
     * 新增订单主表
     */
//    @SaCheckPermission("system:order:add")
    @Log(title = "订单主表", businessType = BusinessType.INSERT)
//    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody OrderBo bo) {
        Long userId = LoginHelper.getUserId();
        if (userId == null) {
            throw new ServiceException("请先登录！");
        }
        bo.setCreatorId(userId);
        return toAjax(orderService.insertByBo(bo));
    }

    /**
     * 修改订单主表
     */
//    @SaCheckPermission("system:order:edit")
    @Log(title = "订单主表", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody OrderBo bo) {
        return toAjax(orderService.updateByBo(bo));
    }

    /**
     * 删除订单主表
     *
     * @param ids 主键串
     */
//    @SaCheckPermission("system:order:remove")
    @Log(title = "订单主表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(orderService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 获取最新订单编号
     */
    @GetMapping("/getOrderNo")
    public R<String> getOrderNo() {
        Long userId = LoginHelper.getUserId();
        if (userId == null) {
            throw new ServiceException("请先登录！");
        }
        return R.ok("获取最新订单编号", orderService.getOrderNo(userId));
    }

    /**
     * 作废订单
     */
//    @SaCheckPermission("system:order:edit")
    @PutMapping("/cancel/{orderId}")
    public R<Void> cancel(@NotNull(message = "主键不能为空") @PathVariable Long orderId) {
        return toAjax(orderService.cancel(orderId));
    }

    /**
     * 查询符合条件的订单 actualAmount 总和
     */
    @GetMapping("/totalAmount")
    public R<BigDecimal> getTotalActualAmount(OrderBo bo) {
        Long userId = LoginHelper.getUserId();
        if (userId == null) {
            throw new ServiceException("请先登录！");
        }
        bo.setCompanyId(userId);
        return R.ok(orderService.getTotalActualAmount(bo));
    }

    /**
     * 添加快递信息
     */
    @PutMapping("/addExpressInfo")
    public R<Void> addExpressInfo(@RequestBody OrderBo bo) {
        Long userId = LoginHelper.getUserId();
        if (userId == null) {
            throw new ServiceException("请先登录！");
        }
        bo.setCreatorId(userId);
        return toAjax(orderService.addExpressInfo(bo));
    }
}
